package com.dex4d.utils;

import android.os.CountDownTimer;
import android.widget.Button;

/**
 * <br>描述：按钮倒计时工具
 */
public class ButtonTimeCounter extends CountDownTimer {

    private static final String COUNT_DOWN_TXT = "(%ds)";
    private static final String RETRY_TXT = "重新发送";
    public static  final long TIME_COUNT = 90L * 1000L;

    private Button button;

    public ButtonTimeCounter(Button button, long millisInFuture, long countDownInterval) {
        this(millisInFuture, countDownInterval);

        this.button = button;
    }

    /**
     * @param millisInFuture    The number of millis in the future from the call
     *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
     *                          is called.
     * @param countDownInterval The interval along the way to receive
     *                          {@link #onTick(long)} callbacks.
     */
    private ButtonTimeCounter(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onTick(long millisUntilFinished) {
        if (button != null) {
            long second = millisUntilFinished / 1000L;
            String strTxt = String.format(COUNT_DOWN_TXT, second);
            button.setText(strTxt);
        }

    }

    @Override
    public void onFinish() {
        if (button != null) {
            button.setEnabled(true);
            button.setText(RETRY_TXT);
            button.setTag(button.getId(), null);
        }
    }

    public void onFailed() {
        super.cancel();
        onFinish();
    }

    public final synchronized CountDownTimer start(boolean btnEnadble) {

        if (button != null) {
            button.setEnabled(btnEnadble);
            button.setTag(button.getId(), new Object());
        }


        return super.start();
    }
}
